package com.lllcr.webcommunication.controller.main;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类简单作用描述
 *
 * @ProjectName: WebCommunication
 * @Package: com.lllcr.webcommunication.controller.main
 * @ClassName: WebSocketController
 * @Description: 类作用描述
 * @Author: leiliangliang
 * @CreateDate: 2022/10/7 17:17
 * @UpdateUser: liangliang
 * @UpdateDate: 2022/10/7 17:17
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2022</p>
 */
@Controller
public class WebSocketController {
    private String prefix = "index";
    /**
     * 页面请求
     * @param cid
     * @return
     */
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav = new ModelAndView("/socket");
        mav.addObject("cid", cid);
        return mav;
    }

    /**
     * 推送消息
     * @param cid
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public String pushToWeb(@PathVariable String cid, String message) {
        try {
            WebSocketServer.sendInfo(message, cid);
        } catch (IOException e) {
            e.printStackTrace();
            return "推送失败";
        }
        return "发送成功";
    }

    @RequestMapping(value = "/socket/upload",method ={RequestMethod.GET,RequestMethod.POST})
    public String upload() {
        return prefix + "/upload";
    }
    @RequestMapping(path = {"uploadFileSave"},method = {RequestMethod.POST})
    public String uploadFileSave(HttpServletRequest request) throws Exception{
        List<String> urls= Stream.of(request.getParameterValues("body[]")).map(body->{
            String base64=body.substring("data:image/jpeg;base64,".length());
            File dir=new File("/zytk/resourcefile/uploadFiles/file/questionImgs/"+ System.currentTimeMillis());
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String fileName= UUID.randomUUID().toString().replace("-", "")+".jpg";
            File img=new File(dir,fileName);
            try(OutputStream out=new FileOutputStream(img)){
                out.write(Base64.decodeBase64(base64));
            }catch(Exception e) {}
            String url="/resourcefile/uploadFiles/file/questionImgs/"+System.currentTimeMillis()+fileName;
            return url;
        }).collect(Collectors.toList()) ;
        //imageUploadSocketHandler.sendMessage(get("id"), new ConditionMap<>().append("urls", urls).toJsonString());
        return "上传成功";
    }
}
